
import datetime

from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render, redirect, HttpResponse
from web import models


class tracer:
    def __init__(self):
        self.user_obj = None
        self.price_policy = None
        self.project = None


class LoginAuth(MiddlewareMixin):

    def process_request(self,request):

        current_path = request.path

        user_id = request.session.get('user_id') #None

        tracer_obj = tracer()
        request.tracer_obj = tracer_obj
        user_obj = models.UserInfo.objects.filter(pk=user_id).first()
        request.tracer_obj.user_obj = user_obj

        # 白名单判断，如果在白名单放行
        if current_path in settings.WHITE_LIST:
            return

        if not user_id:
            return redirect('login')

        # 将当前用户的购买策略加到request对象中，方便后面使用
        tra_obj = models.Transaction.objects.filter(user=request.tracer_obj.user_obj, status=2, ).order_by('-id').first()

        # 过期没有
        # 先看一下是不是免费版的，也就是结束时间为null，如果不是免费版的，拿出结束时间来看一下是不是过期了，如果过期了，我们报错
        end_datetime = tra_obj.end_datetime

        current_time = datetime.datetime.now()
        # 如果过期了
        if end_datetime and end_datetime < current_time:
            # 根据购买记录找到对应的策略,然后将策略保存到request对象中
            price_policy = models.PircePolicy.objects.filter(catogory=1, title='免费').first()
            request.tracer_obj.price_policy = price_policy

        else:
            request.tracer_obj.price_policy = tra_obj.price_policy


        # request.path
        # /web/manage/3/issues/
        # 3 -- id为3 的project对象

    def process_view(self, request, view, args, kwargs):
        # args url无名分组匹配到的参数
        # kwargs url有名分组匹配到的参数
        # 当进入项目详情管理页面的时候，才做提取项目id的操作
        if not request.path.startswith('/web/manage/'):
            return

        # print(view ,args ,kwargs)
        pro_id = kwargs.get('pro_id')

        # 我创建的
        project_obj = models.Project.objects.filter(id=pro_id, creator=request.tracer_obj.user_obj)
        if project_obj:
            request.tracer_obj.project = project_obj.first()
            return

        # 我参与的
        project_obj = models.ProjectUser.objects.filter(project_id=pro_id, user=request.tracer_obj.user_obj)
        if project_obj:
            request.tracer_obj.project = project_obj.first().project
            return

        return redirect('project_list')

        # view
        #<function dashboard at 0x10862f158> () {'pro_id': '7'}










